import { LOGIN_IN, LOGIN_OUT, UPDATE_USERINFO } from './types'
import axios from 'axios'

export const state = () => ({ 
  userInfo:{},  //用户信息
  token:null   //token凭证
});
export const mutations = {  
  [LOGIN_IN](state, data){
    state.status = data;
  },
  [LOGIN_OUT](state, data){
    state.status = data;
  },
  [UPDATE_USERINFO](state, data){
    state.token = data.token;
    state.userInfo = data.user;
  }
};

export const actions = {
  nuxtServerInit({commit}, {req}) { // 将本地服务端数据发送给浏览器
      //根据设计 获取用户信息和token  （可请求后台接口）
      if(req.session && req.session.userInfo){
        commit(UPDATE_USERINFO, req.session.userInfo)
      }
     
  },
  async login({ commit }, res) {
      try {
        const { data } = await axios.post('/api/login',{data:res});
        console.log(data);
        commit(UPDATE_USERINFO,data)
      } catch (error) {
        // if (error.response && error.response.status === 401) {
        //   throw new Error('bad error')
        // }
        // throw error
      }

    }
}

